<?php
declare (strict_types=1);

namespace addons\BuilderPlus\contract;

use addons\BuilderPlus\exception\BuilderException;
use addons\BuilderPlus\facade\Table;

trait MethodsModel
{
    public static function methodsUpdate($param, $options): array
    {
        parent::startTrans();
        try {
            $arguments = Table::getCache($param['builderTableToken']);
            if (empty($arguments)) {
                throw new BuilderException('加载失败，未读取到主页面数据');
            }
            if (empty($param['update'])) {
                throw new BuilderException('没有要修改的数据');
            }

            parent::update($param['update'], [$options['pk'] => $param['id']]);

            Table::trigger('logs', ['type' => 'update', 'param' => $param, 'arguments' => $arguments]);

            parent::commit();
            return ['code' => 1, 'msg' => '修改成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function methodsDelete($param, $options): array
    {
        try {

            $arguments = Table::getCache($param['builderTableToken']);
            if (empty($arguments)) {
                throw new BuilderException('加载失败，未读取到主页面数据');
            }
            if (empty($param['id'])) {
                throw new BuilderException('未选中要删除的数据');
            }

            parent::destroy(explode(',', $param['id']));

            Table::trigger('logs', ['type' => 'delete', 'param' => $param, 'arguments' => $arguments]);

            return ['code' => 1, 'msg' => '已删除'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function methodsSave($arguments, $options): array
    {
        try {

            $param = !empty($options['just']) ? $arguments['data'] : $arguments;
            if (!empty($param[$options['pk']])) {
                $original = parent::where($options['pk'], $param[$options['pk']])->find();
                if (empty($original)) {
                    throw new BuilderException('记录不存在，请检查！');
                }
                parent::update($param);
                if (!empty($options['just'])) {
                    Table::trigger('logs', ['type' => 'save', 'param' => $param]);
                }
            } else {
                parent::create($param);
            }
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param array $map - 查询条件，数组格式
     * @param bool $merge - 是否合并公共查询条件
     * @param string $sort - 排序
     * @param array $with - 是否关键查询
     * 原点 2021年12月22日10:21:58 获取所有数据
     */
    public static function getList($map = [], $merge = true, $sort = 'sort', $with = [], $field = '*', $append = [])
    {
        try {

            $map = $merge ? array_merge($map, ['status' => 1]) : $map;

            $that = !empty($with) ? parent::with($with)->where($map) : parent::where($map);

            return $that->order($sort, 'desc')->field($field)->append($append)->select();

        } catch (\Exception $e) {

            return [];

        }
    }

    /**
     * @param array $map - 查询条件，数组格式
     * @param string $field - 查询字段，默认*
     * @param int $page - 当前页
     * @param int $limit - 每页条数，默认20
     * @param bool $merge - 是否合并is_del，status等公共状态查询条件
     * @param array $with - 是否关键查询
     * @return array
     * 原点 2021年12月22日11:26:47 分页获取数据
     */
    public static function getPageList($map = [],
                                       $field = '*',
                                       $page = 1,
                                       $limit = 20,
                                       $merge = true,
                                       $with = [],
                                       $in = [],
                                       $sort = [],
                                       $like = [],
                                       $time = [], $withoutField = '', $append = [])
    {
        try {

            $map = $merge ? array_merge($map, ['status' => 1]) : $map;


            $that = !empty($with) ? parent::with($with)->where($map) : parent::where($map);
            if (!empty($like)) {
                $that->whereLike($like['field'], '%' . $like['keyword'] . '%');
            }
            if ($time) {
                foreach ($time as $k => $v) {
                    [$start, $end] = explode(' - ', $v['value']);
                    $that->whereBetweenTime($v['key'], $start, $end);
                }
            }
            if (!empty($in)) {
                foreach ($in as $k => $v) {
                    $that->whereIn($k, $v);
                }
            }
            if ($withoutField) {
                $that->withoutField($withoutField);
            } else {
                $that->field($field);
            }
            $count = $that->count();
            $that->page(intval($page), intval($limit));
            if (!$sort) {
                $that->order($merge ? 'sort' : 'create_time', 'desc');
            } else {
                $that->order($sort['key'], $sort['value']);
            }
            $list = $that->select();
            if ($append) {
                $list->append($append);
            }

            $allPage = intval(ceil($count / $limit));
            return ['code' => 1, 'msg' => 'success', 'data' => $list, 'pages' => $allPage];

        } catch (\Exception $e) {

            return ['code' => $e->getCode(), 'message' => $e->getMessage()];

        }
    }
}